const express = require('express');
const router = express.Router();
const db = require('./db');
const bcrypt = require('bcrypt');

// 插入用户数据
const insetUser = async (username, password) => {
  const salt = bcrypt.genSaltSync(10);
  const hashedPassword = bcrypt.hashSync(password, salt);
  return new Promise((resolve, reject) => {
    db.run(
      `INSERT INTO account (username, password, root_path) VALUES ('${username}', '${hashedPassword}', '/home/${username}')`,
      (err) => {
        if (err) {
          reject(err);
        }
        resolve(this.lastID);
      });
  });
};

//检查用户是否存在
const checkUserExist = () => {
  return new Promise((resolve, reject) => {
    db.get('SELECT COUNT(*) as count FROM account', (err, result) => {
      if (err) {
        reject(err);
      }
      resolve(result.count > 0);
    });
  });
};

// 初始化测试用户
const initTestUser = async () => {
  try {
    const userExist = await checkUserExist();
    if (!userExist) {
      await insetUser('zs', 'ddd');
      await insetUser('ls', 'ddd');
      console.log('初始化测试用户成功');
    } else {
      console.log('测试用户已存在,跳过初始化');
    }
  } catch (error) {
    console.error('初始化测试用户失败', error);
  }
};

initTestUser();

// 测试数据库
router.get('/test', (req, res) => {
  db.all('SELECT * FROM account', (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 登录
router.post('/login', (req, res) => {
  const { username, password } = req.body;
  db.get(`SELECT * FROM account WHERE username = ?`, [username], async (err, user) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    if (!user) {
      return res.status(401).json({ error: '用户不存在' });
    }
    try {
      const isMatch = await bcrypt.compare(password, user.password);
      if (isMatch) {
        req.session.user = user;
        res.json({ message: '登录成功'});
      } else {
        res.status(401).json({ error: '密码错误' });
      }
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });
});

//登出
router.post('/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      res.status(500).json({ error: err.message });
    } else {
      res.json({ message: '登出成功' });
    }
  });
});

module.exports = router;
